
package hellfire.system.engine;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import hellfire.system.R;
import hellfire.system.graphics.UI;
import hellfire.system.usbserial.driver.UsbSerialPort;
import hellfire.system.usbserial.util.HexDump;
import hellfire.system.usbserial.util.SerialInputOutputManager;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ScrollView;
import android.widget.TextView;

public class Main extends Activity 
{
    public static UI UI;
    public static Activity Activity;
    public static Thread EngineThread;
    public static Engine Engine;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        // Create a GLSurfaceView instance and set it
        // as the ContentView for this Activity
        UI = new UI(this);
        //UI.getHolder().setFixedSize(768, 1196);
        Activity = this;
        Engine = new Engine();
        EngineThread = new Thread(Engine);
        EngineThread.start();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        setContentView(UI);
        
     
        
    }

    @Override
    protected void onPause() 
    {
        super.onPause();
        UI.onPause();
        //onPause2();
    }

    @Override
    protected void onResume() 
    {
        super.onResume();
        UI.onResume();
        //onResume2();
    }
    
    @Override
	public void onBackPressed()
	{
		if(Engine != null && !Engine.Freeze) 
			Engine.onBack();
	}
    
    public static void MessageBox(final String msg)
	{
		Activity.runOnUiThread(new Runnable() 
		{
			public void run() 
			{
				AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(Activity);                      
			    dlgAlert.setMessage(msg);
			    dlgAlert.setTitle("HellFire2");              
			    dlgAlert.setPositiveButton("OK", null);
			    dlgAlert.setCancelable(false);
			    dlgAlert.create().show();	
			}
		});
	}
	
	public static void MessageBoxStrict(final String msg, final OnClickListener listener)
	{
		Activity.runOnUiThread(new Runnable() 
		{
			public void run() 
			{
				AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(Activity);                      
			    dlgAlert.setMessage(msg);
			    dlgAlert.setTitle("HellFire2");              
			    dlgAlert.setPositiveButton("OK", listener);
			    dlgAlert.setCancelable(false);
			    dlgAlert.create().show();	
			}
		});
	}
	
	
	//----------------------------------------------------------------------
	//----------------------------------------------------------------------
	//----------------------------------------------------------------------
	//----------------------------------------------------------------------
	
	
	private static UsbSerialPort sPort = null;

    private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();

    private SerialInputOutputManager mSerialIoManager;

    private final SerialInputOutputManager.Listener mListener =
    		new SerialInputOutputManager.Listener() {

        @Override
        public void onRunError(Exception e) {
            Log.d("R", "Runner stopped.");
        }

        @Override
        public void onNewData(final byte[] data) {
            Main.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                	Main.this.updateReceivedData(data);
                }
            });
        }
    };

    protected void onPause2() {
        stopIoManager();
        if (sPort != null) {
            try {
                sPort.close();
            } catch (IOException e) {
                // Ignore.
            }
            sPort = null;
        }
        finish();
    }

    
    protected void onResume2() {
        //super.onResume();
        Log.d("R", "Resumed, port=" + sPort);
        if (sPort == null) {
            Log.d("R", "No serial device.");
        } else {
            final UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

            UsbDeviceConnection connection = usbManager.openDevice(sPort.getDriver().getDevice());
            if (connection == null) {
                Log.d("R", "Opening device failed");
                return;
            }

            try {
                sPort.open(connection);
                sPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
            } catch (IOException e) {
                Log.e("R", "Error setting up device: " + e.getMessage(), e);
                try {
                    sPort.close();
                } catch (IOException e2) {
                    // Ignore.
                }
                sPort = null;
                return;
            }
            Log.d("R", "Serial device: " + sPort.getClass().getSimpleName());
        }
        onDeviceStateChange();
    }

    private void stopIoManager() {
        if (mSerialIoManager != null) {
            Log.i("R", "Stopping io manager ..");
            mSerialIoManager.stop();
            mSerialIoManager = null;
        }
    }

    private void startIoManager() {
        if (sPort != null) {
            Log.i("R", "Starting io manager ..");
            mSerialIoManager = new SerialInputOutputManager(sPort, mListener);
            mExecutor.submit(mSerialIoManager);
        }
    }

    private void onDeviceStateChange() {
        stopIoManager();
        startIoManager();
    }

    private void updateReceivedData(byte[] data) {
        final String message = "Read " + data.length + " bytes: \n"
                + HexDump.dumpHexString(data) + "\n\n";
        Log.d("R", message);
    }

    /**
     * Starts the activity, using the supplied driver instance.
     *
     * @param context
     * @param driver
     */
    /*
    static void show(Context context, UsbSerialPort port) {
        sPort = port;
        final Intent intent = new Intent(context, Main.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
        context.startActivity(intent);
    }
    */
}